//
//  HttpManager.m
//  p2p
//
//  Created by mokai on 14-8-13.
//  Copyright (c) 2014年 cloudyoo. All rights reserved.
//


#import "HttpManager.h"


@implementation HttpManager
static HttpManager *manager = nil;

+(HttpManager *)shareManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!manager) {
            manager = [[self alloc]init];
        }
    });
    return manager;
}

+(id)allocWithZone:(NSZone *)zone{
    @synchronized(self){
        if (!manager) {
            manager = [super allocWithZone:zone];
        }
    }
    return manager;
}

-(id)init{
    @synchronized(self)
    {
        if (self = [super init])
        {
        }
    }
    return self;
}

-(void)request:(HttpRequest *)request{
    if (str_isblank(request.url) && str_isblank(request.api))  NSAssert(false, @"url or api not is null");
        
    if (str_isblank(request.url)) {
        request.url = [http_host stringByAppendingString:request.api];
    }
    HttpResponse *response = [HttpResponse new];
    response.request = request;
    [self readCacheData:request];
    
    //无网络连接
    if (![APPUtils isNetworkReach]) {
        response.msg = http_msg_nonetwork;
        response.code = http_code_nonetwork;
        response.isCache = NO;
        request.no(response,response.msg);
        return;
    }
    //发起请求
    debugLog(@"开始加载url:%@?%@",request.url,[self dictParams2String:request.params]);
    //文件上传
    NSMutableURLRequest *req;
    if (request.bodyBlock) {
        req = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:request.url parameters:request.params constructingBodyWithBlock:request.bodyBlock error:nil];
    }else{
        req = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:request.url parameters:request.params error:nil];
    }
    [req setTimeoutInterval:http_time_out_second];//设置请求超时
    
    AFHTTPRequestOperation *afOpt = [[AFHTTPRequestOperation alloc]initWithRequest:req];
    //进度回调
    if (request.uploadBlock) {
        [req setTimeoutInterval:http_img_upload_time_out_second];//图片请求超时
        [afOpt setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
            request.uploadBlock(totalBytesExpectedToWrite,totalBytesWritten);
        }];
    }
    afOpt.responseSerializer = [AFJSONResponseSerializer serializer];
    [afOpt setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        response.isCache = NO;
        //请求成功返回
        debugLog(@"结果:%@",responseObject);
        response.responseObj = responseObject;
        int retCode = response.code =  [responseObject[http_key_code] intValue];
        response.msg = responseObject[http_key_msg];
        if (http_code_ok == retCode) {//成功
            if (request.ok) {
                request.ok(response,response.responseObj);
                [self writeCacheData:request];
            }
        }else{//失败
            if (http_code_session == retCode){//重新登录
//                //让用户自己去登录
//                SIAlertView *alert = [[SIAlertView alloc] initWithTitle:@"温馨提示"
//                                                             andMessage:error_msg_service];
//                [alert setTransitionStyle:SIAlertViewTransitionStyleSlideFromTop];
//                [alert addButtonWithTitle:@"确定" type:SIAlertViewButtonTypeDefault handler:^(SIAlertView *alert){
//                    //[[AppDelegate delegate] showLoginView];
//                }];
//                [alert show];
            }else if(http_code_error==retCode){
                request.no(response,response.msg);
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        response.isCache = NO;
        //请求超时
        debugLog(@"请求报错:%@",error.description);
        response.msg = http_msg_timeout;
        response.code = http_code_error;
        request.no(response,response.msg);
    }];
    request.operator = afOpt;
    [afOpt start];
}

//缓冲功能
-(void)readCacheData:(HttpRequest *)request{//读
    if (!request.httpCache) {
        return;
    }
}

-(void)writeCacheData:(HttpRequest *)request{//写
    if (!request.httpCache) {
        return;
    }
}

-(NSString *)dictParams2String:(NSDictionary *)map{
    NSString  *str = @"";
    for (NSString *key in map.allKeys) {
        if (![str isEqualToString:@""]) {
            str = [str stringByAppendingString:@"&"];
        }
        str = [NSString stringWithFormat:@"%@%@=%@",str, key , [map objectForKey:key]];
    }
    return str;
}
@end
